//
//  QLViewPager.m
//  QLSchool_IOS
//
//  Created by anan on 14-1-14.
//  Copyright (c) 2014年 baobaodev_anan. All rights reserved.
//

#import "QLViewPager.h"

@implementation QLViewPager

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _pageIndicatorHeight = 44;
        _showPageIndicator = YES;
        _tabPageIndicator = [[QLTabPageIndicator alloc]init];
        _tabPageIndicator.viewPager = self;
        _limit = 3;
    }
    return self;
}

/**
 *  初始化
 */
- (void)setup
{
    if (self.scrollView) {
        [self.scrollView removeFromSuperview];
        self.scrollView = nil;
    }
    self.scrollView = [[UIScrollView alloc]init];
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    self.scrollView.scrollsToTop = NO;
    
    CGRect rect;
    if (_showPageIndicator) {
        rect = CGRectMake(0, _pageIndicatorHeight, self.frame.size.width, self.frame.size.height-_pageIndicatorHeight);
        [self initPageIndicator];
    }else{
        rect = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    }
    self.scrollView.frame = rect;
    
    [self addSubview:self.scrollView];
    
    [self addSubview:self.tabPageIndicator];
}

- (void)initPageIndicator
{
    CGRect rect = CGRectMake(0, 0, self.frame.size.width, self.pageIndicatorHeight);
    self.tabPageIndicator.frame = rect;
    self.tabPageIndicator.scrollsToTop = NO;
    self.imageViewTabPageIndicator = [[UIImageView alloc]initWithFrame:rect];
//    [self.imageViewTabPageIndicator setImage:[UIImage imageNamed:@"news_topbar_bg"]];
//    [self addSubview:self.imageViewTabPageIndicator];
//    [self addSubview:self.tabPageIndicator];
}

/**
 *  初始化scrollView
 */
- (void)setupScrollView
{
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    
    int w = self.scrollView.frame.size.width;
    int h = self.scrollView.frame.size.height;
    int count = [self.adapter getCount];
    
    int pages = self.limit<count?self.limit:count;
    //取中间
    pages = ceil(pages/2.0f);
    if (self.limit>count*2) {
        pages = count;
    }
    for (int i=0; i<pages; i++) {
        QLFragment *fragment = [self.adapter getFragment:self position:i];
        [fragment reloadData];
        fragment.contentView.frame = CGRectMake(w*i, 0, w, h);
        [self.scrollView addSubview:fragment.contentView];
        if (i==0) {
            self.currentFragment = fragment;
        }
    }
    
    self.scrollView.contentSize = CGSizeMake(w*count, h);
    
    NSMutableArray *arr = [NSMutableArray array];
    for (int i=0; i<[self.adapter getCount]; i++) {
        NSString *title = [self.adapter getTitle:self position:i];
        [arr addObject:title];
    }
    self.tabPageIndicator.minWidth = 0;
    self.tabPageIndicator.titles = arr;
    [self.tabPageIndicator reloadData];
}

/**
 *  设置数据适配器
 *
 *  @param adapter
 */
- (void)setAdapter:(QLPagerFragmentAdapter *)adapter
{
    if (_adapter) {
        _adapter = nil;
    }
    _adapter = adapter;
    [self setupScrollView];
}

- (void)clearAllFragment
{
    for (int i=0; i<[self.adapter getCount]; i++) {
        QLFragment *fragment = [self.adapter getFragment:self position:i];
        if (fragment.contentView!=nil) {
            [fragment.contentView removeFromSuperview];
            fragment.contentView = nil;
        }
    }
}

/**
 *  重新根据adapter绘制界面
 */
- (void)reloadData
{
    NSMutableArray *arr = [NSMutableArray array];
    for (int i=0; i<[self.adapter getCount]; i++) {
        NSString *title = [self.adapter getTitle:self position:i];
        [arr addObject:title];
    }
    
    int w = self.scrollView.frame.size.width;
    int h = self.scrollView.frame.size.height;
    int count = [self.adapter getCount];
    
    int pages = self.limit<count?self.limit:count;
    //取中间
    pages = ceil(pages/2.0f);
    if (self.limit>count*2) {
        pages = count;
    }
    for (int i=0; i<pages; i++) {
        QLFragment *fragment = [self.adapter getFragment:self position:i];
        [fragment reloadData];
        fragment.contentView.frame = CGRectMake(w*i, 0, w, h);
        [self.scrollView addSubview:fragment.contentView];
    }
    
    self.tabPageIndicator.minWidth = 0;
    self.tabPageIndicator.titles = arr;
    [self.tabPageIndicator reloadData];
    
    self.scrollView.contentSize = CGSizeMake(w*count, h);
}

#pragma mark -
#pragma mark -- UIScrollViewDelegate
// 是否支持滑动至顶部
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView
{
    return YES;
}

// 滑动到顶部时调用该方法
- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
{
    //NSLog(@"scrollViewDidScrollToTop");
}

// scrollView 已经滑动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //NSLog(@"scrollViewDidScroll x:%f",scrollView.contentOffset.x);
}

// scrollView 开始拖动
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //NSLog(@"scrollViewWillBeginDragging");
}

// scrollView 结束拖动
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    //NSLog(@"scrollViewDidEndDragging");
}

// scrollView 开始减速（以下两个方法注意与以上两个方法加以区别）
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    //NSLog(@"scrollViewWillBeginDecelerating");
}

// scrollview 减速停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    int w = self.frame.size.width;
    int index = scrollView.contentOffset.x/w;
    if (index==self.currentIndex) {
        return;
    }
    self.currentIndex = index;
}

- (void)setCurrentIndex:(int)currentIndex animated:(BOOL)animated
{
    _currentIndex = currentIndex;
    CGPoint point = CGPointMake(currentIndex*self.frame.size.width, 0);
    [self.scrollView setContentOffset:point animated:animated];
    if (self.tabPageIndicator) {
        self.tabPageIndicator.select = self.currentIndex;
    }

    int start = currentIndex - self.limit/2;
    int end = currentIndex + self.limit/2;
    int w = self.scrollView.frame.size.width;
    int h = self.scrollView.frame.size.height;
    
    for (int i=start; i<=end; i++) {
        if (i<0) {
            continue;
        }
        if (i>=[self.adapter getCount]) {
            continue;
        }
        QLFragment *fragment = [self.adapter getFragment:self position:i];
        if (fragment.contentView==nil) {
            [fragment reloadData];
            fragment.contentView.frame = CGRectMake(w*i, 0, w, h);
            [self.scrollView addSubview:fragment.contentView];
        }
    }
    
    self.currentFragment = [self.adapter getFragment:self position:currentIndex];
    
    //NSLog(@"scrollViewDidScroll x:%f currentIndex:%d",scrollView.contentOffset.x,self.currentIndex);
    if (self.delegate) {
        if ([self.delegate respondsToSelector:@selector(onPageChange:select:)]) {
            [self.delegate onPageChange:self select:self.currentIndex];
        }
    }
    if (self.tabPageIndicator) {
        self.tabPageIndicator.select = self.currentIndex;
    }
    for (int i = 0; i<[self.adapter getCount]; i++) {
        QLFragment *f = [self.adapter getFragment:self position:i];
        if (f.contentView!=nil) {
            [QLPublic setScrollsToTopWithContentView:f.contentView enable:NO];
        }
    }
    QLFragment *f = self.currentFragment;
    [QLPublic setScrollsToTopWithContentView:f.contentView enable:YES];
}

- (void)setCurrentIndex:(int)currentIndex
{
    [self setCurrentIndex:currentIndex animated:YES];
}

@end
